package com.obrempon.credit.market.ui.dialog

import android.annotation.SuppressLint
import android.content.Context
import android.text.Editable
import android.text.TextWatcher
import android.view.LayoutInflater
import android.view.View
import android.view.inputmethod.EditorInfo
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.GridLayoutManager
import com.obrempon.credit.market.R
import com.obrempon.credit.market.common.CommonDialog
import com.obrempon.credit.market.databinding.ObremponAuthStepWalletAccountAddDialogBinding
import com.obrempon.credit.market.event.ObremponEventPointType
import com.obrempon.credit.market.ui.adapter.ObremponAuthStepWalletAccountTypeApt
import com.obrempon.credit.market.utils.ObremponDensityUtil
import com.obrempon.credit.market.utils.decoration.GridSpacingItemDecoration
import com.obrempon.credit.market.utils.helper.ObremponConfigsHelper
import com.obrempon.credit.market.weight.font.RobotoMediumEditText
import org.json.JSONObject

/**
 * Shipwe
 * @Author wwdeng
 * @CreateTime: 2024/11/21 13:45
 * @Annotation：绑卡dialog
 */
class ObremponWalletAccountAddDialog: CommonDialog {
    private lateinit var binding: ObremponAuthStepWalletAccountAddDialogBinding
    private var mCallback: IDialogCallback? = null
    //事件备注
    private var eventRemark = ""
    //开始选择时间
    private var startTime = 0L;

    var itemAdapter: ObremponAuthStepWalletAccountTypeApt? = null

    constructor(context: Context) : super(context) {}
    constructor(context: Context, callback: IDialogCallback?) : super(context) {
        mCallback = callback
    }

    constructor(context: Context, remark: String,callback: IDialogCallback?) : super(context) {
        mCallback = callback
        eventRemark = remark
    }

    /**
     * 设置点击回调
     */
    fun setOnClick(callback: IDialogCallback){
        this.mCallback = callback
    }

    override fun takeObremponRootView(): View {
        binding = ObremponAuthStepWalletAccountAddDialogBinding.inflate(LayoutInflater.from(context))
        return binding.root
    }

    override fun initObremponView() {
        initWalletAccountTypeListView()
        showTypeDefaultView()
        checkObremponWalletAccountSubmitStatus()
    }

    override fun initObremponListener() {
        setOnClickListener(binding.buttonWalletAccountSubmit)

        binding.editWalletAccount.addTextChangedListener(ITextWatcher)
        binding.editWalletAccountAgain.addTextChangedListener(ITextWatcher)
        binding.editWalletAccount.setInputFocusChangeListener(IEditFocusChangeListener)
        binding.editWalletAccountAgain.setInputFocusChangeListener(IEditFocusChangeListener)
        binding.editWalletAccount.setOnEditorActionListener { _, actionId, _ ->
            if (actionId == EditorInfo.IME_ACTION_DONE){
                binding.editWalletAccount.clearFocus()
                true
            }
            false
        }
        binding.editWalletAccountAgain.setOnEditorActionListener { _, actionId, _ ->
            if (actionId == EditorInfo.IME_ACTION_DONE){
                binding.editWalletAccountAgain.clearFocus()
                true
            }
            false
        }
    }

    override fun takeObremponData() {
        val bindList = arrayListOf<JSONObject>()
        val customize = ObremponConfigsHelper.takeObremponConfigData()
        if (customize != null){
            val walletChannels = customize.optJSONArray("walletChannels")
            if (walletChannels != null && walletChannels.length() > 0){
                for (i in 0..<walletChannels.length()){
                    val item = walletChannels.optJSONObject(i)
                    item.put("isSelect", false)
                    bindList.add(item)
                }
            }
        }
        itemAdapter?.data = bindList
    }

    override fun onObremponViewClick(v: View?) {
        when(v!!.id){
            R.id.buttonWalletAccountSubmit -> {//提交
                val typeObj = getSelectTypeItem() ?: return
                if (takeObremponWalletAccount() != takeObremponWalletAccountComplete()){
                    showTypeErrorView()
                    return
                }
                val duration = System.currentTimeMillis() - startTime
                val submitRemark = "${takeObremponWalletAccount()}$$$duration"
                addEventPointRequestAction(ObremponEventPointType.CLICK.OBREMPON_CLICK_USER_ACCOUNT_ADD_SUBMIT,submitRemark)
                if(mCallback != null){
                    mCallback?.onSubmitParams(typeObj,takeObremponWalletAccount())
                }
                dismiss()
            }
        }
    }

    /**
     * 初始化类型列表
     */
    @SuppressLint("NotifyDataSetChanged")
    private fun initWalletAccountTypeListView() {
        val layoutManager = GridLayoutManager(context,2)
        binding.walletAccountTypeListView.layoutManager = layoutManager
        itemAdapter = ObremponAuthStepWalletAccountTypeApt(binding.walletAccountTypeListView)
        val leftDecoration = ObremponDensityUtil.dp2px(10f)
        binding.walletAccountTypeListView.addItemDecoration(GridSpacingItemDecoration(2, leftDecoration, false))
        binding.walletAccountTypeListView.adapter = itemAdapter!!
        binding.walletAccountTypeListView.itemAnimator = DefaultItemAnimator()
        itemAdapter?.setOnItemChildClickListener { _, childView, position ->
            val model = itemAdapter!!.getItem(position)
            if (childView.id == R.id.walletTypeLayout) {//切换item
                for (i in 0..<itemAdapter!!.itemCount) {
                    val item = itemAdapter!!.getItem(i)
                    if (i == position) {
                        item.put("isSelect", true)
                    } else {
                        item.put("isSelect", false)
                    }
                }
                itemAdapter?.notifyDataSetChanged()
                checkObremponWalletAccountSubmitStatus()
                addEventPointRequestAction(ObremponEventPointType.CLICK.OBREMPON_CLICK_USER_ACCOUNT_ADD_TYPE_CHECK, model.optString("desc"))
            }
        }
    }

    /**
     * 输入框监听
     */
    private val ITextWatcher = object: TextWatcher{
        override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
        }
        override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
        }
        override fun afterTextChanged(s: Editable?) {
            showTypeDefaultView()
            checkObremponWalletAccountSubmitStatus()
        }
    }

    /**
     * 焦点变化监听
     */
    private val IEditFocusChangeListener = object : RobotoMediumEditText.IInputFocusChangeListener{
        override fun onFocusChange(v: View?, hasFocus: Boolean) {
        }
        override fun onCompleteAction(v: View?, remark: String?) {
            var mobile = ""
            if (v?.id == R.id.editWalletAccount){
                mobile = takeObremponWalletAccount()
            } else {
                mobile = takeObremponWalletAccountComplete()
            }
            if (mobile.isNotEmpty()){
                addEventPointRequestAction(ObremponEventPointType.FORM.OBREMPON_FORM_USER_ACCOUNT_ADD_MOBILE,remark!!)
            }
        }
    }

    /**
     * 设置默认样式
     */
    private fun showTypeDefaultView(){
        binding.editWalletAccount.shapeDrawableBuilder
            .setSolidColor(getColor(R.color.transparent))
            .setStrokeColor(getColor(R.color.color_ffeceff3))
            .intoBackground()
        binding.editWalletAccount.setTextColor(getColor(R.color.black))
        binding.editWalletAccountAgain.shapeDrawableBuilder
            .setSolidColor(getColor(R.color.transparent))
            .setStrokeColor(getColor(R.color.color_ffeceff3))
            .intoBackground()
        binding.editWalletAccountAgain.setTextColor(getColor(R.color.black))
        binding.walletAccountErrorLayout.visibility = View.INVISIBLE
    }

    /**
     * 设置号码错误提示
     */
    private fun showTypeErrorView(){
        binding.editWalletAccount.shapeDrawableBuilder
            .setSolidColor(getColor(R.color.color_fffff6f6))
            .setStrokeColor(getColor(R.color.color_fff55555))
            .intoBackground()
        binding.editWalletAccount.setTextColor(getColor(R.color.color_fff55555))
        binding.editWalletAccountAgain.shapeDrawableBuilder
            .setSolidColor(getColor(R.color.color_fffff6f6))
            .setStrokeColor(getColor(R.color.color_fff55555))
            .intoBackground()
        binding.editWalletAccountAgain.setTextColor(getColor(R.color.color_fff55555))
        binding.walletAccountErrorLayout.visibility = View.VISIBLE
    }

    /**
     * 切换Ajouter按钮是否可点击
     */
    fun checkObremponWalletAccountSubmitStatus(){
        if (getSelectTypeItem() != null && takeObremponWalletAccount().isNotEmpty() && takeObremponWalletAccountComplete().isNotEmpty() && (takeObremponWalletAccount() == takeObremponWalletAccountComplete())){
            binding.buttonWalletAccountSubmit.isEnabled = true
        } else {
            binding.buttonWalletAccountSubmit.isEnabled = false
        }
    }

    /**
     * 获取选择的账户类型
     */
    private fun getSelectTypeItem(): JSONObject?{
        var obj: JSONObject? = null
        for (item in itemAdapter!!.data) {
            if (item.optBoolean("isSelect", false)){
                obj = item
                break
            }
        }
        return obj
    }

    /**
     * 获取输入的手机号码
     */
    private fun takeObremponWalletAccount(): String{
        return binding.editWalletAccount.text.toString()
    }

    /**
     * 获取确认手机号码
     */
    private fun takeObremponWalletAccountComplete(): String{
        return binding.editWalletAccountAgain.text.toString()
    }

    interface IDialogCallback {
        //按钮点击
        fun onClick(view: View?)
        //确认
        fun onSubmitParams(typeObj: JSONObject,phoneNumber: String)
    }

    override fun show() {
        super.show()
        startTime = System.currentTimeMillis()
    }

    override fun onStart() {
        super.onStart()
        addEventPointRequestAction(ObremponEventPointType.DIALOG.OBREMPON_DIALOG_USER_ACCOUNT_ADD_SHOW,eventRemark)
    }

    override fun dismiss() {
        super.dismiss()
        addEventPointRequestAction(ObremponEventPointType.DIALOG.OBREMPON_DIALOG_USER_ACCOUNT_ADD_DISMISS,eventRemark)
    }
}